(function ($) {
    var page = "weibo";
    layui.use(['element', 'form', 'layer', 'laytpl'], function () {
        var model = $(".weibo-content");
        var layer = layui.layer;
        var form = layui.form;
        var laytpl = layui.laytpl;

        //是否有任务在执行
        var processing = false;

        var table = $(".weibo-table").table({
            columns: [
                {
                    "name": "title",
                    "display": "微博标题"
                },
                {
                    "name": "author",
                    "display": "作者"
                },
                // {
                //     "name": "tag",
                //     "display": "标签"
                // },
                // {
                //     "name": "expireTime",
                //     "display": "过期时间",
                //     "render": function (rowData) {
                //         rowData.expireTimeInHour = (rowData.expireTime / 60).toFixed(0);
                //         return rowData.expireTimeInHour + "小时";
                //     }
                // },
                {
                    "display": "操作",
                    render: function (rowData) {
                        return "<div class='opt-btn-group'><span class='edit-item'><i class=\"layui-icon\">&#xe642;</i>编辑</span>" +
                            "<span class='delete-item'><i class=\"layui-icon\">&#xe640;</i>删除</span></div>";
                    }
                }
            ],
            url: "/hycj/news",
            showTitle: false,
            formatData: function (data) {
                return data.datas;
            },
            params: {
                channelId: 2
            }
        });

        //编辑对话框
        model.on("click", ".edit-item", function (e) {
            var rowData = table.getRowData($(e.target).closest("tr"));
            $.getJsonData("/hycj/news/" + rowData.id).done(function (data) {
                data.datas.expireTimeInHour = (data.datas.expireTime / 60).toFixed(0);
                if (data.datas.image) {
                    data.datas.imageArray = data.datas.image.split(",");
                } else {
                    data.datas.imageArray = [];
                }
                laytpl($("#weiboForm").html()).render({
                    model: "updateWeiboForm",
                    data: data.datas
                }, function (content) {
                    layer.open({
                        type: 1,
                        title: "更新微博",
                        content: content,
                        area: "600px",
                        maxHeight: app.clientHeight() - 50
                        // ,
                        // success: function () {
                        //     $("[name='tag']").tagsinput({
                        //         tagClass: 'big',
                        //         confirmKeys: [44, 65292, 9, 32]
                        //     });
                        // }
                    });
                });
            });
        });

        //创建对话框
        model.on("click", ".create-item", function (e) {
            laytpl($("#weiboForm").html()).render({
                model: "addWeiboForm",
                data: {}
            }, function (content) {
                layer.open({
                    type: 1,
                    title: "创建微博",
                    content: content,
                    area: "600px",
                    maxHeight: app.clientHeight() - 50
                    // ,success: function () {
                    //     $("[name='tag']").tagsinput({
                    //         tagClass: 'big',
                    //         confirmKeys: [44, 65292, 9, 32]
                    //     });
                    // }
                });
            });
        });

        //删除对话框
        model.on("click", ".delete-item", function (e) {
            var layer = layui.layer;
            var selectedData = table.getRowData($(e.target).closest("tr"));
            layer.msg('您确认删除<br>' + selectedData.title, {
                time: 5000, //5s后自动关闭
                btn: ['确认', '取消']
                , btn1: function (index, layero) {
                    $.getJsonData("/hycj/news"
                        , {id: selectedData.id}
                        , {type: "Delete"})
                        .done(function () {
                            layer.msg("删除完成");
                            table.refresh();
                        }).fail(function () {
                        layer.msg("删除失败, 请稍后重试!");
                    });
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        });

        //搜索
        form.on('submit(searchWeiboForm)', function (data) {
            if (!data.form) {
                return false
            }
            table.refresh(data.field);
            return false;
        });

        //新增
        form.on('submit(addWeiboForm)', function (data) {
            if (processing || !data.form) {
                return false
            }
            processing = true;
            data.field.expireTime = data.field.expireTime * 60;

            //将附图表单内容组装成逗号相隔的字符串
            var contentCombine = "";
            $("[name='cover']", data.form).each(function (index, e) {
                contentCombine += "," + $(e).val();
            });

            if (contentCombine) {
                data.field.image = contentCombine.substring(1);
            }
            $.getJsonData("/hycj/news", data.field, {type: "Post"}).done(function (data) {
                if (data.code == '500') {
                    layer.msg(data.message, {icon: 2});
                } else {
                    layer.closeAll();
                    layer.msg('操作成功', {icon: 6});
                    table.refresh();
                }
                processing = false;
            }).fail(function () {
                processing = false;
            });
            return false;
        });

        //更新
        form.on('submit(updateWeiboForm)', function (data) {
            if (processing || !data.form) {
                return false
            }
            processing = true;
            data.field.expireTime = data.field.expireTime * 60;

            //将附图表单内容组装成逗号相隔的字符串
            var contentCombine = "";
            $("[name='cover']", data.form).each(function (index, e) {
                contentCombine += "," + $(e).val();
            });

            if (contentCombine) {
                data.field.image = contentCombine.substring(1);
            }
            $.getJsonData("/hycj/news", data.field, {type: "Put"}).done(function (data) {
                if (data.code == '500') {
                    layer.msg(data.message, {icon: 2});
                } else {
                    app.showSuccess();
                    table.refresh();
                }
                processing = false;
            }).fail(function () {
                processing = false;
            });
            return false;
        });


        form.verify({
            expireTime: function (value, item) {
                var expireTimeIntVal;
                try {
                    expireTimeIntVal = parseInt(value)
                } catch (error) {
                    return "过期时间只能为数字";
                }
                if (expireTimeIntVal < 6 || expireTimeIntVal >= 24) {
                    return "过期时间只能为6（包括）到24（不包括）小时";
                }
            }
        });

        app.bindPageEvents(page, function () {
            //增加海报表单项
            $(document).on("click", ".weibo-form .add-cover-btn", function (e) {
                if ($(".cover").length >= 3) {
                    layer.msg("附图不能超过3张", {icon: 2});
                    return false;
                }
                var $addBtn = $(e.currentTarget);
                moon.uploader({
                    //上传成功的回调，回调数据为文件上传的路径。格式如下：[{path:xxx},{path:xxx}]
                    callback: function (uploadRet) {
                        $(uploadRet).each(function (index, uploadItem) {
                            $addBtn.before(" <div class=\"cover\">\n" +
                                "<i class=\"layui-icon remove-cover\">&#x1007;</i>" +
                                "                        <input type=\"hidden\" name=\"cover\" required lay-verify=\"required\"\n" +
                                "                               autocomplete=\"off\" value=\"" + uploadItem.path + "\"\n" +
                                "                               class=\"layui-input show-uploader\">\n" +
                                "                        <img src=\"" + uploadItem.path + "\" class=\"cover-item\"/>\n" +
                                "                    </div>");
                            if ($(".cover").length >= 3) {
                                $(".add-cover-btn").hide();
                            }
                        });
                    }
                });
            });

            //移除海报表单项
            $(document).on("click", ".weibo-form .remove-cover", function (e) {
                var $coverDiv = $(e.target).closest(".cover");
                $coverDiv.remove();
                $(".add-cover-btn").show();
            });

            //上传logo
            $(document).on("click", ".weibo-form .add-logo", function (e) {
                var $addBtn = $(e.currentTarget);
                moon.uploader({
                    //上传成功的回调，回调数据为文件上传的路径。格式如下：[{path:xxx},{path:xxx}]
                    callback: function (uploadRet) {
                        var uploadItem = uploadRet[0];
                        $addBtn.closest(".logo-img-container").html("<img src=\"" + uploadItem.path + "\" class=\"logo-item add-logo\"/>");
                        $("[name='logo']").val(uploadItem.path);
                    }
                });
            });
        });
    });
})(jQuery);